package com.zmn.oms.third.baidu_app.service;

import com.alibaba.fastjson.JSON;
import com.zmn.base.product.common.consts.BaseProductConsts;
import com.zmn.base.product.common.dto.product.ec.ProductPicBaseDRO;
import com.zmn.base.product.common.dto.product.ec.ProductPicGroupDRO;
import com.zmn.base.product.common.query.product.ec.ProductPicQuery;
import com.zmn.base.product.dubbo.interfaces.product.ec.ProductPicListRemoteService;
import com.zmn.common.constant.StatusConsts;
import com.zmn.common.dto2.ResponseDTO;
import com.zmn.common.utils.collection.CollectionUtil;
import com.zmn.common.utils.date.DateUtil;
import com.zmn.common.utils.number.NumberUtil;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.manager.redis.RedisManager;
import com.zmn.oms.business.interfaces.notifylog.OrderNotifyLogBService;
import com.zmn.oms.common.constant.OrderConsts;
import com.zmn.oms.common.constant.OrderLogConsts;
import com.zmn.oms.common.constant.OrderStatusConsts;
import com.zmn.oms.common.constant.RedisKeyConsts;
import com.zmn.oms.common.dto.ResultDTO;
import com.zmn.oms.common.exception.OmsBaseException;
import com.zmn.oms.common.utils.HttpUtil;
import com.zmn.oms.model.entity.notifylog.OrderNotifyLog;
import com.zmn.oms.model.entity.work.OrderWork;
import com.zmn.oms.model.entity.work.OrderWorkLogChange;
import com.zmn.oms.services.interfaces.work.OrderWorkService;
import com.zmn.oms.third.baidu_app.BaiduAppConsts;
import com.zmn.oms.third.baidu_app.dto.*;
import com.zmn.oms.zmn.business.interfaces.open.OrderChangeNotifyService;
import com.zmn.oms.zmn.business.interfaces.open.OrderNewNotifyService;
import com.zmn.pay.common.constant.PayConsts;
import com.zmn.saas.common.dro.app.UserBaiduRelationDRO;
import com.zmn.saas.dubbo.interfaces.app.AppRemoteService;
import com.zmn.ums.dubbo.utils.DubboConsts;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;

/**
 * 类描述：百度小程序渠道订单状态同步处理
 *
 * @author XieWenBing
 * @date 2020/08/31 16:34
 */

@Slf4j
@Service("baiduAppNotifyService")
public class BaiduAppNotifyServiceImpl implements OrderChangeNotifyService, OrderNewNotifyService {

    @Resource
    RedisManager redisManager;

    @Reference(version = DubboConsts.INTERFACE_VERSION, check = false)
    protected AppRemoteService appRemoteService;

    @Reference(version = com.zmn.base.plat.engine.common.constant.DubboConsts.INTERFACE_VERSION , check = false)
    protected ProductPicListRemoteService productPicListRemoteService;

    @Autowired
    protected OrderWorkService orderWorkService;

    @Autowired
    protected OrderNotifyLogBService orderNotifyLogBService;

    @Override
    public void notifyChange(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException{

        if (!BaiduAppConsts.POWER_ON) {
            log.info("【{}】<订单状态同步> 功能关闭。", BaiduAppConsts.CHANNEL_NAME);
            return;
        }

        log.info("【{}】<订单状态同步> ,状态信息:[{}]。", BaiduAppConsts.CHANNEL_NAME,orderWorkLogChange.toString());

        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("订单状态同步异常，参数为null");
        }

        int logType = orderWorkLogChange.getLogType().intValue();
        BaiduAppResponse baiduAppResponse = null;

        switch (logType) {
            // 确认
            case OrderLogConsts.ORDER_LOG_TYPE_CONFIRM:

                baiduAppResponse = this.syncUpdateOrder(orderWorkLogChange);
                if (Objects.nonNull(baiduAppResponse)) {
                    this.saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_INPUT,baiduAppResponse);
                }
                this.syncOrderStatus(orderWorkLogChange.getOrderId(),orderWorkLogChange.getWorkId(),BaiduAppConsts.STATUS_ORDER_CONFIRM);
                break;
            // 修改和改产品
            case OrderLogConsts.ORDER_LOG_TYPE_UPDATE:
            case OrderLogConsts.ORDER_LOG_TYPE_MODIFY_PRODUCT:
                baiduAppResponse = this.syncUpdateOrder(orderWorkLogChange);
                if (Objects.nonNull(baiduAppResponse)) {
                    this.saveSyncResult(orderWorkLogChange, OrderStatusConsts.ORDER_STATUS_INPUT, baiduAppResponse);
                }
                break;
            // 取消、失败、弃单
            case OrderLogConsts.ORDER_LOG_TYPE_CANCEL:
            case OrderConsts.ORDER_OP_TYPE_FAIL:
            case OrderConsts.ORDER_OP_TYPE_DISCARD:
                this.syncOrderStatus(orderWorkLogChange.getOrderId(),orderWorkLogChange.getWorkId(),BaiduAppConsts.STATUS_ORDER_CANCEL);
                break;
            // 完成
            case OrderLogConsts.ORDER_LOG_TYPE_COMPLETE:
                this.syncOrderStatus(orderWorkLogChange.getOrderId(),orderWorkLogChange.getWorkId(),BaiduAppConsts.STATUS_ORDER_FINISH);
                break;
            default:
                return;
        }
    }

    @Override
    public void notifyNewOrder(OrderWorkLogChange orderWorkLogChange) throws OmsBaseException {

        if (!BaiduAppConsts.POWER_ON) {
            log.info("【{}】<订单状态同步-新订单> 功能关闭。", BaiduAppConsts.CHANNEL_NAME);
            return;
        }

        log.info("【{}】<订单状态同步-新订单>,订单状态:[{}] ",BaiduAppConsts.CHANNEL_NAME,orderWorkLogChange.toString());
        if (Objects.isNull(orderWorkLogChange)) {
            throw new OmsBaseException("新单录入同步异常，参数为null");
        }

        BaiduAppResponse baiduAppResponse = this.syncUpdateOrder(orderWorkLogChange);
        if (Objects.nonNull(baiduAppResponse)) {
            this.saveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_INPUT,baiduAppResponse);
        }
    }

    /**
     * 获取通信token
     * @return String
     */
    private String getAccessToken() {

        // 先从redis里面读取
        if (Objects.nonNull(redisManager)) {
            String accessToken = redisManager.get(RedisKeyConsts.BAIDU_APP_TOKEN_REDIS_KEY);
            if (StringUtils.isNotEmpty(accessToken)) {
                return accessToken;
            }
        }

        // 发送http请求获取token
        BaiduAppGetTokenRequest getTokenRequest = new BaiduAppGetTokenRequest();
        getTokenRequest.setClientId(BaiduAppConsts.APP_KEY);
        getTokenRequest.setClientSecret(BaiduAppConsts.APP_SECRET);
        getTokenRequest.setGrantType("client_credentials");
        getTokenRequest.setScope("smartapp_snsapi_base");

        // 转换为map
        Map<String,String> params = new HashMap<>(4);
        params.put("grant_type",getTokenRequest.getGrantType());
        params.put("client_id",getTokenRequest.getClientId());
        params.put("client_secret",getTokenRequest.getClientSecret());
        params.put("scope",getTokenRequest.getScope());

        String response = sendRequest(BaiduAppConsts.TOKEN_URL, params,null);
        if (StringUtils.isEmpty(response)) {
            log.info("【{}】获取token失败",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }

        // 取得返回的内容
        BaiduAppGetTokenResponse getTokenResponse = null;
        try {
            // 解析JSON
            getTokenResponse = JSON.parseObject(response,BaiduAppGetTokenResponse.class);
            if (Objects.isNull(getTokenResponse)) {
                log.info("【{}】获取token失败,解析应答数据错误【{}】",BaiduAppConsts.CHANNEL_NAME,response);
            }
        } catch (Exception e) {
            log.info("【{}】获取token失败,解析应答数据异常【{}】",BaiduAppConsts.CHANNEL_NAME,response);
            return null;
        }

        String accessToken = getTokenResponse.getAccessToken();
        // 保存到redis里面
        if (Objects.nonNull(redisManager)) {
            // 设置token有效期为固定的一天
            redisManager.setex(RedisKeyConsts.BAIDU_APP_TOKEN_REDIS_KEY, accessToken, BaiduAppConsts.TOKEN_TIMEOUT);
        }

        return accessToken;
    }

    /**
     * 同步新单录入或订单信息更改
     * @param orderWorkLogChange
     */
    private BaiduAppResponse syncUpdateOrder(OrderWorkLogChange orderWorkLogChange) {

        Long orderId = orderWorkLogChange.getOrderId();
        Long workId = orderWorkLogChange.getWorkId();
        boolean isNewOrder = orderWorkLogChange.isNewOrder();

        // 如果不为新单，则判断是否已经同步订单导入
        if (!isNewOrder) {
            isNewOrder = !this.findSaveSyncResult(orderWorkLogChange,OrderStatusConsts.ORDER_STATUS_INPUT);
        }

        // 获取百度小程序对应的open id
        String openId = this.getOpenId(orderId,workId);
        if (StringUtils.isEmpty(openId)) {
            log.info("【{}】新单录入/订单更新 同步失败-未能获取open id",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }

        String token = this.getAccessToken();
        if (StringUtils.isEmpty(token)) {
            log.info("【{}】新单录入/订单更新 同步失败-未能获取token",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }

        // 工单信息
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,workId);
        if (Objects.isNull(orderWork)) {
            log.info("【{}】新单录入/订单更新 同步失败-查找不到工单信息",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }

        log.info("【{}】新单录入/订单更新  同步,【{}】【{}】，订单【{}】",BaiduAppConsts.CHANNEL_NAME,openId,token,orderWork.toString());
        // 订单同步信息
        BaiduAppUpdateOrderData updateOrderData = new BaiduAppUpdateOrderData();
        updateOrderData.setAppId(BaiduAppConsts.APP_KEY);
        updateOrderData.setCateId(BaiduAppConsts.CATE_ID);
        updateOrderData.setOrderId(String.valueOf(orderId));
        updateOrderData.setCreateTime(orderWork.getCreateTime().getTime()/1000);
        updateOrderData.setModifyTime(DateUtil.getNowTimestamp());
        updateOrderData.setTitle("啄木鸟家庭维修");
        updateOrderData.setStatus(isNewOrder ? BaiduAppConsts.STATUS_NEW_ORDER : BaiduAppConsts.STATUS_ORDER_CONFIRM);

        // 产品和支付信息设置
        BaiduAppOrderExtend orderExtend = new BaiduAppOrderExtend();
        BaiduAppOrder baiduAppOrder = new BaiduAppOrder();
        orderExtend.setAppOrder(baiduAppOrder);
        updateOrderData.setOrderExtend(orderExtend);

        BaiduAppOrderProduct baiduAppOrderProduct = new BaiduAppOrderProduct();
        BaiduAppOrderPayment baiduAppOrderPayment = new BaiduAppOrderPayment();
        BaiduAppOrderDetail baiduAppOrderDetail = new BaiduAppOrderDetail();

        List<BaiduAppOrderProduct> appOrderProducts = new ArrayList<>(1);
        appOrderProducts.add(baiduAppOrderProduct);
        baiduAppOrder.setOrderPayment(baiduAppOrderPayment);
        baiduAppOrder.setOrderProducts(appOrderProducts);
        baiduAppOrder.setOrderDetail(baiduAppOrderDetail);

        // 产品信息
        baiduAppOrderProduct.setId(String.valueOf(orderWork.getProductId()));
        baiduAppOrderProduct.setName(orderWork.getShowServCategName() + "-" + orderWork.getShowProductGroupName());
        baiduAppOrderProduct.setQuantity(1);
        baiduAppOrderProduct.setPayPrice(0);
        baiduAppOrderProduct.setPrice(0);

        // 产品图片
        String imageProduct = getOrderProductImage(orderWork);
        if (StringUtil.isNotBlank(imageProduct)) {
            List<String> imgList = new ArrayList<>(1);
            imgList.add(imageProduct);
            baiduAppOrderProduct.setImageList(imgList);
        }

        // 价格信息
        Boolean isOrderPay = Boolean.TRUE;
        if (Objects.isNull(orderWork) || orderWork.getPayStatus() != PayConsts.PAY_STATUS_DONE) {
            isOrderPay = Boolean.FALSE;
        }
        baiduAppOrderPayment.setMethod(BaiduAppConsts.PAY_METHOD);
        baiduAppOrderPayment.setAmount(orderWork.getMasterAmount());
        baiduAppOrderPayment.setIsPayment(isOrderPay);

        Date payTime = orderWork.getPayTime();
        if (isOrderPay && Objects.nonNull(payTime)) {
            baiduAppOrderPayment.setTime(Long.valueOf(orderWork.getPayTime().getTime()/1000).intValue());
        } else {
            baiduAppOrderPayment.setTime(0);
        }

        // 订单详情跳转
        baiduAppOrderDetail.setName("");
        baiduAppOrderDetail.setStatus(2);
        baiduAppOrderDetail.setSwanSchema(BaiduAppConsts.APP_ORDER_DETAIL_ADDR.replace("%oms_order_id%",String.valueOf(orderId)));

        // 生成请求参数
        String requestPath = isNewOrder ? BaiduAppConsts.SYNC_NEW_ORDER_PATH : BaiduAppConsts.SYNC_UPDATE_ORDER_PATH;
        String requestUrl = BaiduAppConsts.APP_URL + requestPath;
        Map<String,String> params = new HashMap<>(2);
        params.put("access_token",token);
        params.put("open_id",openId);

        // 发送请求
        String request = String.format("{\"Data\":[%s]}",JSON.toJSONString(updateOrderData));
        String response = this.sendRequest(requestUrl,params,request);
        if (StringUtils.isEmpty(response)) {
            log.info("【{}】新单录入/订单更新 同步失败-返回数据为空",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }

        log.info("【{}】新单录入/订单更新 同步,参数；【{}】，请求数据；【{}】，应答数据；【{}】",BaiduAppConsts.CHANNEL_NAME,params.toString(),request,response);
        // 解析应当数据
        try {

            BaiduAppResponse baiduAppResponse = JSON.parseObject(response,BaiduAppResponse.class);
            if (Objects.isNull(baiduAppResponse)) {
                log.info("【{}】新单录入/订单更新 同步失败-解析应答数据失败【{}】",BaiduAppConsts.CHANNEL_NAME,response);
            } else {
                log.info("【{}】新单录入/订单更新 同步完成，code:【{}】,消息提示:【{}】",BaiduAppConsts.CHANNEL_NAME,baiduAppResponse.getErrno(),baiduAppResponse.getMsg());
            }

            return baiduAppResponse;
        } catch (Exception e) {
            log.info("【{}】新单录入/订单更新 同步失败-解析应答数据异常【{}】",BaiduAppConsts.CHANNEL_NAME,response);
        }

        return null;
    }

    /**
     * 同步订单的状态信息
     *
     * @param orderId
     * @param workId
     * @param status
     */
    private void syncOrderStatus(Long orderId, Long workId,Integer status) {

        // 获取请求access token
        String token = this.getAccessToken();
        if (StringUtils.isEmpty(token)) {
            log.info("【{}】同步订单状态失败-未能获取token",BaiduAppConsts.CHANNEL_NAME);
            return;
        }

        // 获取百度小程序对应的open id
        String openId = this.getOpenId(orderId,workId);
        if (StringUtils.isEmpty(openId)) {
            log.info("【{}】同步订单状态失败-未能获取open id",BaiduAppConsts.CHANNEL_NAME);
            return;
        }

        log.info("【{}】同步订单状态,【{}】【{}】【{}】",BaiduAppConsts.CHANNEL_NAME,openId,token,status);

        // 生成请求数据
        BaiduAppUpdateOrderStatus updateOrderStatus = new BaiduAppUpdateOrderStatus();
        updateOrderStatus.setCateId(BaiduAppConsts.CATE_ID);
        updateOrderStatus.setOrderId(String.valueOf(orderId));
        updateOrderStatus.setAppId(BaiduAppConsts.APP_KEY);
        updateOrderStatus.setStatus(status);

        // 生成请求参数
        String requestUrl = BaiduAppConsts.APP_URL + BaiduAppConsts.SYNC_UPDATE_STATUS_PATH;
        Map<String,String> params = new HashMap<>(2);
        params.put("access_token",token);
        params.put("open_id",openId);

        // 发送请求
        String request = String.format("{\"Data\":[%s]}",JSON.toJSONString(updateOrderStatus));
        String response = this.sendRequest(requestUrl,params,request);
        if (StringUtils.isEmpty(response)) {
            log.info("【{}】同步订单状态失败-返回数据为空",BaiduAppConsts.CHANNEL_NAME);
            return;
        }

        log.info("【{}】同步订单状态,参数；【{}】，请求数据；【{}】，应答数据；【{}】",BaiduAppConsts.CHANNEL_NAME,params.toString(),request,response);
        // 解析应当数据
        try {

            BaiduAppResponse baiduAppResponse = JSON.parseObject(response,BaiduAppResponse.class);
            if (Objects.isNull(baiduAppResponse)) {
                log.info("【{}】同步订单状态失败-解析应答数据失败【{}】",BaiduAppConsts.CHANNEL_NAME,response);
            } else {
                log.info("【{}】同步订单状态完成，code:【{}】,消息提示:【{}】",BaiduAppConsts.CHANNEL_NAME,baiduAppResponse.getErrno(),baiduAppResponse.getMsg());
            }
        } catch (Exception e) {
            log.info("【{}】同步订单状态失败-解析应答数据异常【{}】",BaiduAppConsts.CHANNEL_NAME,response);
        }
    }

    /**
     * 获取订单产品的图片地址
     *
     * @param orderWork
     * @return
     */
    private String getOrderProductImage(OrderWork orderWork) {

        if (Objects.isNull(orderWork)) {
            return null;
        }

        Integer productId = NumberUtil.isNullOrZero(orderWork.getShowProductId()) ? orderWork.getProductId() : orderWork.getShowProductId();
        if (NumberUtil.isNullOrZero(productId)) {
            log.info("【{}】获取订单产品id失败",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }

        log.debug("【{}】获取订单产品图片地址：{}",BaiduAppConsts.CHANNEL_NAME,productId);
        ProductPicQuery build = ProductPicQuery
                .builder()
                .productId(productId)
                .showType(NumberUtil.isNullOrZero(orderWork.getShowProductId()) ? BaseProductConsts.ERP_SHOW_TYPE : BaseProductConsts.EC_SHOW_TYPE)
                .build();
        ResponseDTO<List<ProductPicGroupDRO>> productPictureDROResponseDTO = productPicListRemoteService.listDROByQuery(build);
        if (Objects.isNull(productPictureDROResponseDTO) || !productPictureDROResponseDTO.isSuccess() || CollectionUtil.isNullOrEmpty(productPictureDROResponseDTO.getData())) {
            log.info("【{}】#ServProductPictureListRemoteService#getServProductPictureByProductId# 失败",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }
        log.debug("【{}】获取订单产品图片地址结果{}",BaiduAppConsts.CHANNEL_NAME,JSON.toJSONString(productPictureDROResponseDTO));

        ProductPicGroupDRO productPicDRO = productPictureDROResponseDTO.getData()
                .stream()
                .filter(e -> CollectionUtil.isNotNullOrEmpty(e.getProductSmallPics()))
                .sorted(Comparator.comparing(ProductPicGroupDRO::getShowType))
                .findAny().orElse(null);
        if (Objects.isNull(productPicDRO)) {
            productPicDRO = productPictureDROResponseDTO.getData()
                    .stream()
                    .filter(e -> CollectionUtil.isNotNullOrEmpty(e.getProductBigPics()))
                    .sorted(Comparator.comparing(ProductPicGroupDRO::getShowType))
                    .findAny().orElse(null);
        }
        if (Objects.isNull(productPicDRO)) {
            return null;
        }

        String imageUrl = null;
        if (CollectionUtil.isNotNullOrEmpty(productPicDRO.getProductSmallPics())) {
            imageUrl = productPicDRO.getProductSmallPics()
                    .stream()
                    .filter(e -> StringUtil.isNotBlank(e.getPicLink()))
                    .sorted(Comparator.comparing(ProductPicBaseDRO::getShowType))
                    .map(ProductPicBaseDRO::getPicLink)
                    .findAny().orElse(null);
        }
        if (StringUtil.isBlank(imageUrl)) {
            if (CollectionUtil.isNotNullOrEmpty(productPicDRO.getProductBigPics())) {
                imageUrl = productPicDRO.getProductBigPics()
                        .stream()
                        .filter(e -> StringUtil.isNotBlank(e.getPicLink()))
                        .sorted(Comparator.comparing(ProductPicBaseDRO::getShowType))
                        .map(ProductPicBaseDRO::getPicLink)
                        .findAny().orElse(null);
            }
        }

        log.info("【{}】获取订单产品图片地址,{},{}",BaiduAppConsts.CHANNEL_NAME,productId,imageUrl);
        
        return imageUrl;
    }

    /**
     * 发送http请求
     * @param url
     * @param params
     * @param body
     * @return
     * @throws OmsBaseException
     */
    private String sendRequest(String url, Map<String,String> params, String body){

        if (StringUtils.isBlank(url)) {
            log.info("【{}】发送请求失败，URL参数不能为空",BaiduAppConsts.CHANNEL_NAME);
            return null;
        }

        String response = "";
        for (int i=0; i<3; i++) {
            try {
                response = HttpUtil.httpsPost(url,body,params);
                if (StringUtil.isNotBlank(response)) {
                    break;
                }
            } catch (Exception exception) {
                log.info("【{}】发送请求失败,{}",BaiduAppConsts.CHANNEL_NAME,Objects.nonNull(exception)? exception.getMessage():"网络请求异常");
            }
        }

        return response;
    }

    /**
     * 获取百度小程序的open id
     * @param orderId
     * @param workId
     * @return
     */
    private String getOpenId(Long orderId, Long workId) {

        // 查找OrderWork信息
        OrderWork orderWork = orderWorkService.findOrderWorkByKey(orderId,workId);
        if (Objects.isNull(orderWork)) {
            return null;
        }

        // 根据工单的userId获取百度小程序用户信息
        UserBaiduRelationDRO baiduRelation = getBaiduInfo(orderWork);
        if (Objects.isNull(baiduRelation)) {
            return null;
        }

        return baiduRelation.getOpenId();
    }

    /**
     * 根据工单信息获取百度小程序相关信息
     *
     * @param orderWork
     * @return
     */
    private UserBaiduRelationDRO getBaiduInfo(OrderWork orderWork) {
        ResponseDTO<UserBaiduRelationDRO> resp;
        try {
            resp = appRemoteService.getUserBaiduInfoByUserIdAndChannelId(orderWork.getUserId(), orderWork.getChannelId());
            log.info("订单号【{}】获取百度信息getUserBaiduInfoByUserIdAndChannelId 入参userId={},出参{}", orderWork.getOrderId(), orderWork.getUserId(), resp);

            if (!resp.isSuccess() || Objects.isNull(resp.getData())) {
                log.info("订单号【{}获取getUserBaiduInfoByUserIdAndChannelId 百度信息失败", orderWork.getOrderId());
                return null;
            }
        } catch (Exception ex) {
            log.error(String.format("订单号%s 获取百度信息getUserBaiduInfoByUserIdAndChannelId接口异常了:%s", orderWork.getOrderId(), ex.getMessage()), ex);
            return null;
        }

        return resp.getData();
    }

    /**
     * 保存状态同步结果信息
     * @param orderWorkLogChange
     * @param orderStatus
     * @param result
     */
    private void saveSyncResult(OrderWorkLogChange orderWorkLogChange, int orderStatus, BaiduAppResponse result) {
        if (Objects.isNull(result) || Objects.isNull(orderWorkLogChange)) {
            return;
        }

        OrderNotifyLog orderNotifyLog = new OrderNotifyLog();
        orderNotifyLog.setMqMsgKey(orderWorkLogChange.getMqMsgKey());
        orderNotifyLog.setOrderId(orderWorkLogChange.getOrderId());
        orderNotifyLog.setChannelId(orderWorkLogChange.getChannelId());
        orderNotifyLog.setOrderStatus(orderWorkLogChange.getStatus());
        orderNotifyLog.setOrderResultStatus(orderWorkLogChange.getResultStatus());
        orderNotifyLog.setNotifyStatus(String.valueOf(orderStatus));
        orderNotifyLog.setType(OrderConsts.ORDER_NOTIFY_TYPE_CHANGE);
        orderNotifyLog.setNotifyTime(DateUtil.getNow());

        String resultMsg = result.getMsg();
        orderNotifyLog.setNotifyResultMsg(String.format("[%s]-%s",
                OrderStatusConsts.getOrderStatusName(orderStatus), io.netty.util.internal.StringUtil.isNullOrEmpty(resultMsg) ? "" : resultMsg ));

        ResultDTO resultDTO = new ResultDTO();
        resultDTO.setStatus(result.getErrno() == BaiduAppConsts.RESPONSE_CODE_SUCCESS? StatusConsts.STATUS_SUCCESS : StatusConsts.STATUS_ERROR);
        resultDTO.setData(orderNotifyLog);

        orderNotifyLogBService.saveNotifyLog(resultDTO);
    }

    /**
     * 查询状态同步结果信息
     * @param orderWorkLogChange
     * @param orderStatus
     * @return boolean
     */
    private boolean findSaveSyncResult(OrderWorkLogChange orderWorkLogChange, int orderStatus) {

        // 根据订单id查找保存的是数据
        Long orderId = orderWorkLogChange.getOrderId();
        List<OrderNotifyLog> orderNotifyLogs = orderNotifyLogBService.listByOrderId(orderId);
        if (Objects.isNull(orderNotifyLogs)) {
            return false;
        }

        for (OrderNotifyLog item : orderNotifyLogs) {
            if (Objects.equals(String.valueOf(orderStatus), item.getNotifyStatus())
                    && Objects.equals(StatusConsts.STATUS_SUCCESS, item.getNotifyResultStatus())) {
                return true;
            }
        }

        return false;
    }

    /**
     * 测试
     * @param args
     */
    public static void main(String[] args) {

        // 发送http请求获取token
        BaiduAppGetTokenRequest getTokenRequest = new BaiduAppGetTokenRequest();
        getTokenRequest.setClientId(BaiduAppConsts.APP_KEY);
        getTokenRequest.setClientSecret(BaiduAppConsts.APP_SECRET);
        getTokenRequest.setGrantType("client_credentials");
        getTokenRequest.setScope("smartapp_snsapi_base");

        // 转换为map
        Map<String,String> params = new HashMap<>(4);
        params.put("grant_type",getTokenRequest.getGrantType());
        params.put("client_id",getTokenRequest.getClientId());
        params.put("client_secret",getTokenRequest.getClientSecret());
        params.put("scope",getTokenRequest.getScope());

        // 取得返回的内容
        BaiduAppGetTokenResponse getTokenResponse = null;
        String response = "";
        try {
            response = HttpUtil.httpsPost(BaiduAppConsts.TOKEN_URL,JSON.toJSONString(getTokenRequest),params);
            if (StringUtils.isEmpty(response)) {
                System.out.println("获取token失败");
            }

            // 解析JSON
            getTokenResponse = JSON.parseObject(response,BaiduAppGetTokenResponse.class);
            if (Objects.isNull(getTokenResponse)) {
                System.out.println("获取token失败," + response);
            }
        } catch (Exception e) {
            System.out.println("获取token失败,解析应答数据异常 - " + response);
        }
    }
}
